package com.wl.zlmanage.interceptor;

import com.wl.zlmanage.utils.FilterMatchUtil;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * Created by Administrator on 2018/3/9.
 */
public class ActionInterceptor extends HandlerInterceptorAdapter {
    private static Logger logger = Logger.getLogger(ActionInterceptor.class);

    private static final List<String> UN_NEED_LOGIN_ACTION = new ArrayList<String>();

    static {
        UN_NEED_LOGIN_ACTION.add("login.do");
        UN_NEED_LOGIN_ACTION.add("logout.do");
        UN_NEED_LOGIN_ACTION.add("getEncKey.do");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute("username");
        String url = request.getRequestURI();

        // 无需校验的请求，如：登录，注册，忘记密码等
        if (FilterMatchUtil.isEndWithListStr(url, UN_NEED_LOGIN_ACTION)) {
            return true;
        }

        String requestType = request.getHeader("X-Requested-With");
        if(StringUtils.isNotBlank(requestType) && requestType.equalsIgnoreCase("XMLHttpRequest")){
            if(org.springframework.util.StringUtils.isEmpty(userName)){
                returnError(response, "timeout", true);
                return false;
            }
        }else{
            if(org.springframework.util.StringUtils.isEmpty(userName)){
                String html = "";
                response.sendRedirect("/login.do");
                return false;
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    private void returnError(HttpServletResponse response, String errorMessage, boolean isTimeOut)
    {
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = null;
        try
        {
            if(isTimeOut){
                response.setHeader("sessionstatus", "timeout");
                response.sendError(518, "session timeout");
            }
            out = response.getWriter();
            out.append(errorMessage);
        }
        catch (IOException e)
        {
            logger.error("ActionFilter response error:", e);
        }
        finally
        {
            if (out != null)
            {
                out.close();
            }
        }
    }
}
